package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.PostDao;
import com.example.dao.UserDao;
import com.example.domain.Post;
import com.example.domain.TableData;
import com.example.domain.User;
import com.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class PostServiceImpl extends ServiceImpl<PostDao, Post> implements PostService {
    @Autowired
    private PostDao postDao;
    @Autowired
    private UserDao userDao;

    @Override
    public TableData<Post> getPage(Integer page, Integer limit, String username, String content) {

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper();
        lqw.like(!StringUtils.isEmpty(username), User::getUsername, username);

        List<User> userList = userDao.selectList(lqw);

        List userIdList = new ArrayList();
        for (User user : userList) {
            userIdList.add(user.getId());
        }


        QueryWrapper<Post> queryWrapper = new QueryWrapper();
        queryWrapper.like(!StringUtils.isEmpty(content), "content", content);
        queryWrapper.in("user_id", userIdList);

        IPage<Post> ipage = new Page(page, limit);
        IPage<Post> postIPage = postDao.selectPage(ipage, queryWrapper);
        TableData<Post> tableData = new TableData<>();
        tableData.setCount(postIPage.getTotal());
        tableData.setCode(0);
        tableData.setMsg("");

        for (Post post : postIPage.getRecords()) {
            User user = userDao.selectById(post.getUserId());

            post.setUsername(user.getUsername());
        }


        tableData.setData(postIPage.getRecords());
        return tableData;
    }
}
